package com.minglead.springboot.common.redis;


import com.minglead.springboot.common.config.Global;
import com.minglead.springboot.common.utils.ObjectUtils;
import com.minglead.springboot.common.utils.SpringContextHolder;
import com.minglead.springboot.common.utils.StringUtils;
import redis.clients.jedis.JedisCluster;

/**
 * Jedis Cache 工具类
 * 集群版，必须配置好集群xml
 * spring-jedis.xml 此文件在applicationContext.xml 被引入
 * 
 */
public class JedisUtilsCluster {

	private static JedisCluster jedisCluster = ((JedisCluster)SpringContextHolder.getBean("jedisCluster"));
	
	public static String businessCacheKeyPrefix = null;
	static{
		String redisCacheKeyPrefix = Global.getConfig("redisCacheKeyPrefix");
		businessCacheKeyPrefix = StringUtils.isEmpty(redisCacheKeyPrefix)?"springboot_cache_":redisCacheKeyPrefix;
	}
	
	public static final String keyPefixRedBlackCatalog = "redBlackCatalog_";//红黑榜统计相关前缀		
	/**
	 * 默认失效时间
	 * @return
	 */
	public static Integer getCacheTimeOut(){	
		Integer CACHE_TIME_OUT = Integer.parseInt(Global.getConfig("redis.cache_time_out"));
		return CACHE_TIME_OUT;
	}

	/**
	 * 获取SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static byte[] get(String key) {
		String key0 = businessCacheKeyPrefix+key;
		byte[] o = jedisCluster.get(JedisUtilsCluster.getBytesKey(key0));
		return o;
	}
	
	/**
	 * 写入SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static void put(String key, Object value) {
		String key0 = businessCacheKeyPrefix+key;
		jedisCluster.set(JedisUtilsCluster.getBytesKey(key0), ObjectUtils.serialize(value));
		jedisCluster.expire(key0, JedisUtilsCluster.getCacheTimeOut());
		
	}
	public static void clear(String key) {
		String key0 = businessCacheKeyPrefix+key;
		jedisCluster.set(JedisUtilsCluster.getBytesKey(key0), new byte[]{});
		jedisCluster.expire(key0, 0);//立即超时
		
	}
	
	/**
	 * 获取byte[]类型Key
	 * @param key
	 * @return
	 */
	private static byte[] getBytesKey(Object object){
		if(object instanceof String){
    		return StringUtils.getBytes((String)object);
    	}else{
    		return ObjectUtils.serialize(object);
    	}
	}
	
	
	public static void main(String[] args){
		JedisUtilsCluster.put("springboot_01", "this is springboot project test");
		String data = (String) ObjectUtils.unserialize(JedisUtilsCluster.get("springboot_01"));
		System.out.println("取到的数据是："+data);
	}
	
}
